package com.hmdp.interceptor;

import com.hmdp.utils.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 衷岚
 * @version 1.0
 */
@Component
@Slf4j
public class GlobalInterceptor implements HandlerInterceptor {
    //刷新token有效期

    @Autowired
    private RedisTemplate redisTemplate;

    private static final String AUTHORIZATION = "authorization";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(AUTHORIZATION);
        log.info("token:{}", token);
        if (token == null) {
            return true;
        }
        if(redisTemplate.opsForHash().entries(RedisConstants.LOGIN_USER_KEY+token) == null){
            return true;
        }

        //刷新有效期
        redisTemplate.expire(RedisConstants.LOGIN_USER_KEY+token,RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        return true;


    }
}
